/* global $, visoConfig, Mustache, uuid, jsPlumb */

var faaa = (function() {
	var _thisNode = null;
	var timeoutId = null;
	var areaId = '#folwMain';

	jsPlumb.ready(jsPlumbMain);
	

	// 放入拖动节点
	function dropNode(dataset, ui, obj) {
		var dataObj = ui.position;
		var left = parseInt(ui.offset.left - $(obj).offset().left);
		var top = parseInt(ui.offset.top - $(obj).offset().top);
		dataObj.id = uuid.v1();
		dataObj.top = top;
		dataObj.left = left;
		dataObj.jnode = dataset.jnode;
		dataObj.jnodeClass = dataset.jnodeClass;
		dataObj.jnodeHtml = ui.helper.html();
		console.log("《跟踪》创建节点：template.dataObj", dataObj);
		var targetHtml = renderHtml(dataset.template, dataObj);
		$(areaId).append(targetHtml); //追加元素

		initSetNode(dataObj); // 初始化节点设置
	}

	// 初始化节点设置
	function initSetNode(dataObj) {
		var id = dataObj.id;
		// jsPlumb.draggable(id, {containment: 'parent'})
		addDraggable(id);

		var isvisible = false;
		if("judge" == dataObj.jnode) {
			isvisible = true; //判断节点显示Label标签
		}
		//设置四周端点
		visioConfig.baseArchors.forEach(function(key) {
			jsPlumb.addEndpoint(
				id, {
					anchors: key,
					connectorOverlays: [
						["Arrow", {
							width: 10,
							length: 10,
							location: 1,
							id: "arrow",
							visible: isvisible
						}],
						["Label", {
							label: "条件",
							id: "myLabel",
							cssClass: "connectorLabel",
							visible: isvisible,
							events: {
								"click": function(label, evt) {
									console.log("clicked on label for connection", label.component);
								}
							}
						}]
					]
				},
				visioConfig.hollowCircle);
		});
		
		//新增可删除的close元素
		$("#" + id).on("dblclick", ".jnode-box", function(conn, originalEvent) {
			clearTimeout(timeoutId); 
			var obj = $(this);
			//下面写双击事件要执行的代码
			if(confirm("确定要删除节点和相关连线吗？")) {
				console.log("《跟踪》删除节点：", conn);
				jsPlumb.removeAllEndpoints(obj.parent().attr("id"));
				obj.parent().remove();
			}
			
		}).on("click", ".jnode-box", function(conn, originalEvent) {
			clearTimeout(timeoutId);
			_thisNode = $(this);
			timeoutId = window.setTimeout(function (){
				$("input[name='nodeTitle']").val(_thisNode.text().replace(/"/g,"'").replace(/[\t\n]/g,""))
				$(".nodeTitle").show();
			},300);
		});
	}

	// 让元素可拖动
	function addDraggable(id) {
		jsPlumb.draggable(id, {
			containment: 'parent'
		});
	}

	// 利用mustache模板工具，渲染html
	function renderHtml(templateId, dataObj) {
		return Mustache.render($("#" + templateId).html(), dataObj);
	}

	//初始化连接线的文本。
	function initConnection(connection) {
		var labelText = connection.sourceId.substring(15) + "-" + connection.targetId.substring(15);
		var startText = connection.source.innerText;
		var endText = connection.target.innerText;
		labelText = startText + "->" + endText;
		connection.getOverlay("myLabel").setLabel(labelText);
	}

	// 主要入口
	function jsPlumbMain() {
		jsPlumb.setContainer('diagramContainer-main');
		
		//双点击了连接线, 支持删除连线
		jsPlumb.bind('dblclick', function(conn, originalEvent) {
			if(confirm("确定要删除节点和相关连线吗？")) {
				jsPlumb.detach(conn)
			}
		});

		jsPlumb.bind("connection", function(connInfo, originalEvent) {
			console.log("《跟踪》成功链接节点：", connInfo.connection);
			initConnection(connInfo.connection);
		});

		jsPlumb.bind("connectionDrag", function(connection) {
			console.log("《跟踪》开始链接节点：", connection);
		});

		jsPlumb.bind("connectionDragStop", function(connection) {
			console.log("《跟踪》结束链接节点：", connection);
		});

		//定义可拖拽控件
		$('.jnode-box').draggable({
			helper: 'clone',
			scope: 'ss'
		});

		//定义可拖拽释放
		$(areaId).droppable({
			scope: 'ss',
			drop: function(event, ui) {
				//创建新节点
				dropNode(ui.draggable[0].dataset, ui, $(this));
			}
		});
	}
	

	
	//页面加载时识别缓存JSON
	window.onload = function(){
		// 遍历节点
		if(localStorage.getItem('node')){
			let node = JSON.parse(localStorage.getItem('node'));
			console.log("node：", node);
	        for(let i = 0;i<node.length;i++){
	        	var blockClass = node[i].BlockClass.replace("jnode-box ","");
	        	var dataObj = { top: node[i].BlockY, left: node[i].BlockX, id: node[i].BlockId, jnode: node[i].BlockJnode, jnodeClass: blockClass, jnodeHtml: node[i].BlockContent }
			    var targetHtml = renderHtml("jnode-template", dataObj);
			    $('#folwMain').append(targetHtml); //追加元素
			    initSetNode(dataObj);
	        }
	    }
		// 遍历线条
	    if(localStorage.getItem('ligature')){
	        let ligature = JSON.parse(localStorage.getItem('ligature'));
			console.log("ligature：", ligature);
			// 将节点的连线还原
	        for(let i = 0;i<ligature.length;i++){
	            jsPlumb.ready(function (){
	            	jsPlumb.connect(
	            		{
	            			source:ligature[i].PageSourceId, 
	            			target:ligature[i].PageTargetId,
        					anchor: [ligature[i].PageSourceAnchor, ligature[i].PageTargetAnchor],
						  	paintStyle: { stroke: 'lightgray', strokeWidth: 3 },
						  	endpointStyle: { fill: 'lightgray', outlineStroke: 'darkgray', outlineWidth: 2 },
						  	overlays: [ ['Arrow', { width: 12, length: 12, location: 1 }] ]
						  }, 
						  visioConfig.hollowCircle
	            	);
				    jsPlumb.draggable(ligature[i].PageSourceId);
				    jsPlumb.draggable(ligature[i].PageTargetId);
	            })
	        }
	    }
	}
	
	/**
	 * 监听按钮点击事件
	 */
	$('body').on('click', '.layui-btn-event', function(e){
		var type = $(this).data('type');
		active[type] ? active[type].call(this, e.target) : '';
	});
	var active = {
		reset: function(e) { /** 重置 */
			location.reload();
		},
		submit: function(e) { /** 提交 */
			// 遍历节点
	    	var blocks = [];
		    $("#folwMain .jnode-box").each(function (idx,elem) {
		        var $elem = $(elem);
		        blocks.push({
		            BlockId: $elem.parent().attr('id'),
		            BlockJnode: $elem.parent().attr('jnode'),
		            BlockContent: $elem.html().replace(/"/g,"'").replace(/[\t\n]/g,""),
		            BlockClass: $elem.attr('class').replace("jnode-box ",""),
		            BlockX: parseInt($elem.parent().css("left"), 10),
		            BlockY: parseInt($elem.parent().css("top"), 10)
		        });
		    });
		    
			// 遍历线条
		    var connects = [];
		    $.each(jsPlumb.getAllConnections(), function (idx,connection) {
		    	var sourceAnchor,targetAnchor;
		    	if(connection.endpoints[0].anchor.type){
		    		// 新增的连线
		    		sourceAnchor = connection.endpoints[0].anchor.type;
		    		targetAnchor = connection.endpoints[1].anchor.type;
		    	}else{
		    		// 原来的连线
		    		sourceAnchor = connection.endpoints[0].anchor.anchors[0].type;
		    		targetAnchor = connection.endpoints[0].anchor.anchors[1].type;
		    	}
		    	connects.push({
		            ConnectionId: connection.id,
		            PageSourceId: connection.sourceId,
		            PageSourceAnchor: sourceAnchor.replace("Middle","").replace("Center",""),
		            PageTargetId: connection.targetId,
		            PageTargetAnchor: targetAnchor.replace("Middle","").replace("Center","")
		            /*,Uuids: connection.getUuids()*/
		        });
		    });
		    
			// 将数据转换格式后存储
		    let ligature = JSON.stringify(connects);
		    // 将多出来的 \ 去掉
		    let node = JSON.stringify(blocks).replace(/\\/g,"");
		    localStorage.setItem('ligature',ligature);
		    localStorage.setItem('node',node);
		    console.log("ligature："+ligature)
		    console.log("node："+node);
		},
		nodeSubmit: function(e) { 
			// 保存节点标题
			var nodeTitle = $("input[name='nodeTitle']").val();
			_thisNode.find("span").text(nodeTitle);
			var fontSize = 14;
			if(nodeTitle.length<=3){
				fontSize = 14;
			}else if(nodeTitle.length<=5){
				fontSize = 10;
			}else if(nodeTitle.length<=6){
				fontSize = 8;
			}else if(nodeTitle.length<=8){
				fontSize = 6;
			}else{
				fontSize = 5;
			}
			_thisNode.find("span").css("font-size",fontSize+"pt");
		},
		nodeClose: function(e) { 
			// 关闭节点标题
			$(".nodeTitle").hide();
		}
	};
	
})()
